﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Diagnostics.Contracts;
using System.ComponentModel.Composition;

namespace Kooboo.Commerce.Repositories
{
    [Export(typeof(IAddressRepository))]
    public partial class EntityRepositories:IAddressRepository
    {
       

        IQueryable<IAddress> IAddressRepository.Addresses
        {
            get
            {
                return this.DataReaderContext.Addresses;
            }
        }

        public void Post(int customerId, IAddress address)
        {
            Contract.Requires(address != null);

            var item = new Address()
            {
                CustomerId = customerId,
                Address1 = address.Address1,
                Address2 = address.Address2,
                City = address.City,
                CountryCode = address.Country== null?null:address.Country.CountryCode,
                FirstName = address.FirstName,
                LastName = address.LastName,
                Phone = address.Phone,
                Postcode = address.Postcode,
                State = address.State
            };

            this.DataWriterContext.Addresses.InsertOnSubmit(item);
            this.DataWriterContext.SubmitChanges();

            address.Id = item.Id;
        }

        public void Put(int customerId, IAddress address)
        {
            Contract.Requires(address != null);

            var item = this.DataWriterContext.Addresses
                .Where(i => i.Id == address.Id)
                .FirstOrDefault();

            if (item == null)
            {
                throw new KeyNotFoundException("Address:" + address.Id);

            }

            item.CustomerId = customerId;
            item.Address1 = address.Address1;
            item.Address2 = address.Address2;
            item.City = address.City;
            item.CountryCode = address.Country == null ? null : address.Country.CountryCode;
            
            item.FirstName = address.FirstName;
            item.LastName = address.LastName;
            item.Phone = address.Phone;
            item.Postcode = address.Postcode;
            item.State = address.State;

            this.DataWriterContext.SubmitChanges();
        }

        public void Delete(int customerId, IAddress address)
        {
            if (address != null)
            {
                var item = this.DataWriterContext.Addresses
                .Where(i => i.Id == address.Id)
                .FirstOrDefault();

                if (item != null)
                {
                    this.DataWriterContext.Addresses.DeleteOnSubmit(item);
                    this.DataWriterContext.SubmitChanges();
                }
            }
        }

    }
}
